﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 修改人：x
 * 时间：
 * 修改说明：
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>using System;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace seejee_Backendium.Data.Services
{
    public class OperatorOnlineMonitor : BackgroundService
    {
        private readonly IServiceScopeFactory _scopeFactory;
        private readonly IConfiguration _configuration;

        public OperatorOnlineMonitor(IServiceScopeFactory scopeFactory, IConfiguration configuration)
        {
            _scopeFactory = scopeFactory;
            _configuration = configuration;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                using var scope = _scopeFactory.CreateScope();
                string connStr = _configuration.GetConnectionString("Default");
                using (SqlConnection connection = new SqlConnection(connStr))
                {
                    connection.Open();
                    string query = @"
                UPDATE SEBI_Operator
                SET bOperatorOnLine = 0
                WHERE bOperatorOnLine = 1 AND DATEDIFF(MINUTE, LastActiveTime, GETDATE()) > 10";
                    using (SqlCommand command = new SqlCommand(query, connection))
                    {
                        command.ExecuteNonQuery();
                    }
                    //  清空符合条件的Token
                    string clearTokenQuery = @"
                UPDATE SEBI_Operator
                SET Token = NULL 
                WHERE  DATEDIFF(MINUTE, LastActiveTime, GETDATE()) > 10";
                    using (SqlCommand tokenCommand = new SqlCommand(clearTokenQuery, connection))
                    {
                        tokenCommand.ExecuteNonQuery();
                    }
                }
                await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); // 每1分钟检测一次
            }
        }
    }
}
